<?php

namespace app\api\model\bargain;

use app\api\model\User;
use app\common\model\bargain\TaskHelp as TaskHelpModel;
use Symfony\Component\Console\Helper\Helper;

/**
 * 砍价任务助力记录模型
 * Class TaskHelp
 * @package app\api\model\bargain
 */
class TaskHelp extends TaskHelpModel
{
    /**
     * 隐藏的字段
     * @var array
     */
    protected $hidden = [
        'wxapp_id',
        'create_time',
    ];
	
	/**
	 * 限制用户当日的砍价次数使用
	 * 根据用户id 获取当前用户当天的砍价次数
	 * @param $userId
	 * @return list
	 */
	public static function getUserTaskHelpTimes($userId){
		// 当天0点时间戳
		$start = strtotime(date('Ymd').'00:00:00');
		$end = $start+(3600*24);
		// 时间区间查询
		return $list = (new static)->where('user_id',$userId)->where('is_creater',0)->where('create_time','between time',[$start,$end])->count();
	}

    /**
     * 获取助力列表记录
     * @param $taskId
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getListByTaskId($taskId)
    {
        // 获取列表数据
        $list = (new static)->with(['user'])
            ->where('task_id', '=', $taskId)
            ->order(['create_time' => 'desc'])
            ->select();
        // 隐藏会员昵称
        foreach ($list as &$item) {
            $item['user']['nickName'] = \substr_cut($item['user']['nickName']);
        }
        return $list;
    }

    /**
     * 新增记录
     * @param $task
     * @param $userId
     * @param $cutMoney
     * @param $isCreater
     * @return false|int
     */
    public function add($task, $userId, $cutMoney, $isCreater = false)
    {
        $ip = request()->ip(0,true);
        $ua = $user_agent =  $_SERVER['HTTP_USER_AGENT'];

        // 获取user agent
        $user_agent = $this->getUserAgent($user_agent);
        
        return $this->save([
            'task_id' => $task['task_id'],
            'active_id' => $task['active_id'],
            'user_id' => $userId,
            'cut_money' => $cutMoney,
            'is_creater' => $isCreater,
            'wxapp_id' => static::$wxapp_id,
            'ip' => $ip,
            'equipment' => $ua,
            'user_agent' => $user_agent,
            'agent_md5' => md5($user_agent),
        ]);
    }

    /**
     * 根据砍价活动id获取正在砍价的助力信息列表
     * @param $activeId
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getHelpListByActiveId($activeId)
    {
        $list = $this
            ->with('user')  // todo: 废弃
            ->alias('help')
            ->field(['help.user_id', 'user.nickName', 'user.avatarUrl'])
            ->join('user', 'user.user_id = help.user_id')
            ->join('bargain_task task', 'task.task_id = help.task_id')
            ->where('help.active_id', '=', $activeId)
            // is_creater 只统计发起人
            //->where('help.is_creater', '=', 1)
            ->where('task.status', '=', 1)
            ->where('task.is_delete', '=', 0)
            ->group('help.user_id')
            ->limit(3)
            ->select()->toArray();

        if(empty($list)){
            $user = new User;
            $count = $user->count();
            $ids = [];
            $length = 0;
            do {
                $user_id = mt_rand(1, $count);
                if(!in_array($user_id,$ids)){
                    $ids[] = $user_id;
                    $length++;
                }
                if ($length >= 3) {
                    break;
                }
            } while (1);
            $list = $user->whereIn('user_id',$ids)->field(['user_id', 'nickName', 'avatarUrl'])->select();
        }else{
            $user = new User;
            $count = $user->count();
            $length = count($list);
            $ids = array_column($list, 'user_id');
            if($length < 3){
                do {
                    $user_id = mt_rand(1, $count);
                    if(!in_array($user_id,$ids) && !in_array($user_id,[1,6])){
                        $ids[] = $user_id;
                        $length++;
                    }
                    if ($length >= 3) {
                        break;
                    }
                } while (1);
                $list = $user->whereIn('user_id',$ids)->field(['user_id', 'nickName', 'avatarUrl'])->select()->toArray();
                shuffle($list);
            }
        }

        return $list;
    }

    /**
     * 根据砍价活动id获取正在砍价的助力人数
     * @param $activeId
     * @return int|string
     * @throws \think\Exception
     */
    public function getHelpCountByActiveId($activeId)
    {
        return $this->alias('help')
            ->join('user', 'user.user_id = help.user_id')
            ->join('bargain_task task', 'task.task_id = help.task_id')
            ->where('help.active_id', '=', $activeId)
            // is_creater 只统计发起人
//            ->where('help.is_creater', '=', 1)
			// status == 1 统计进行中的，去掉后统计累积的
            // ->where('task.status', '=', 1)
            ->where('task.is_delete', '=', 0)
            ->group('help.user_id')
            ->count();
    }

}